package com.iflytek.autofly.setting.biz.voice;

import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.SystemProperties;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.iflytek.autofly.navisetting.NaviSetting;
import com.iflytek.autofly.setting.R;
import com.iflytek.autofly.setting.biz.base.BaseFragment;
import com.iflytek.autofly.setting.biz.base.CommonRadioButtonBean;
import com.iflytek.autofly.setting.biz.base.CommonRadioGroupAdpt;
import com.iflytek.autofly.setting.widget.InnerListView;
import com.iflytek.autofly.utils.FlyLog;
import com.iflytek.autofly.voicecore.tts.TtsInitListener;
import com.iflytek.autofly.voicecore.tts.TtsListener;
import com.iflytek.autofly.voicecore.tts.TtsSession;
import com.iflytek.autofly.voicecore.tts.TtsSessionManager;
import com.iflytek.sunflower.FlowerCollector;

/**
 * <b>Description: </b>声音设置的fragment<br/>
 * <b>Change History:</b><br/>
 * <table border="1">
 * <tr>
 * <td><b>user</b></td>
 * <td><b>date</b></td>
 * <td><b>time</b></td>
 * <td><b>reason</b></td>
 * </tr>
 * <tr>
 * <td>JunLuan@iflytek.com</td>
 * <td>2015年10月14日</td>
 * <td>上午11:34:14</td>
 * <td>创建此文件</td>
 * </tr>
 * </table>
 *
 * @author JunLuan@iflytek.com
 */
public class VoiceFragment extends BaseFragment {
    protected static final String TAG = "VoiceFragment";
    private static final String WAKEUP_PROPERTY = "persist.sys.autofly.wakeup";
    private static final String SRECHO_PROPERTY = "persist.sys.autofly.srecho";
    private static final String GENDER_PROPERTY = "persist.sys.autofly.gender";
    private static final boolean SRECHO_DEFAULT_VALUE = false;
    private static final boolean WAKEUP_PROPERTY_DEFAULT_VALUE = true;
    private static final boolean GENDER_PROPERTY_DEFAULT_VALUE = false;
    private static final String[] CMD = {"wakeup", "gender", "speaker"};

    private ToggleButton mWakeUpTbn;
    //private ToggleButton mSrEchoTbn;
    private TextView mSpeakerTv;
    private InnerListView mSpeakerLv;
    private SpeakerConfig mSpeakerConfig;

    private NaviSetting mNaviSetting;

    private TtsSession mTtsSession;
    private AudioManager mAudioManager;
    private volatile boolean mhasAudioFocusGained = false;
    private AudioManager.OnAudioFocusChangeListener mFocusListener = new AudioManager.OnAudioFocusChangeListener() {
        @Override
        public void onAudioFocusChange(int focusChange) {
            FlyLog.d(TAG, "FocusChange " + focusChange);
            if (AudioManager.AUDIOFOCUS_LOSS == focusChange) {
                if (mTtsSession != null) {
                    mTtsSession.stopSpeak();
                }
                mAudioManager.abandonAudioFocus(mFocusListener);
                FlyLog.d(TAG, "AudioFocus Loss");
            } else if (AudioManager.AUDIOFOCUS_LOSS_TRANSIENT == focusChange) {
                FlyLog.d(TAG, "AudioFocus Loss TRANSIENT");
            } else if (AudioManager.AUDIOFOCUS_GAIN == focusChange) {
                FlyLog.d(TAG, "AudioFocus gain");
            }
        }
    };
    private ToggleButton mGenderRecTbn;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState);
        init(view);
        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public void onDestroy() {
        FlyLog.d(TAG, "destory client");
        mNaviSetting.destoryClient(getActivity());
        if (mTtsSession != null) {
            mTtsSession.sessionStop();
        }
        if (mhasAudioFocusGained) {
            mAudioManager.abandonAudioFocus(mFocusListener);
            mhasAudioFocusGained = false;
        }
        TtsSessionManager.getInstance().destroyClient();
        super.onDestroy();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mNaviSetting = NaviSetting.registerListener(getActivity(), new NaviSetting.IBindListener() {
            @Override
            public void onServiceStatusChanged(NaviSetting.AidlStatus status) {
                FlyLog.d(TAG, "status: " + status);
            }
        });
        TtsSessionManager.getInstance().initClient(getActivity(), new TtsInitListener() {
            @Override
            public void onTtsInited(boolean b, int i) {
                FlyLog.d(TAG, "state: " + b + "errId: " + i);
            }
        });
        mAudioManager = (AudioManager) getActivity().getSystemService(Context.AUDIO_SERVICE);
    }

    private void init(View v) {
        addUnit(R.layout.voicewakeup);
//        addUnit(R.layout.srecho);
        addHiddenUnit(R.layout.genderrec);
        addUnit(R.layout.speaker, R.layout.speaker_sub, new OnExpandChangeListener() {
            @Override
            public void onExpandChanged(boolean isExpanded) {
                if (isExpanded) {
                    mSpeakerTv.setVisibility(View.GONE);
                } else {
                    mSpeakerTv.setVisibility(View.VISIBLE);
                }
            }
        }, null);
        addHiddenUnit(R.layout.aboutsystem);


        mWakeUpTbn = (ToggleButton) v.findViewById(R.id.voice_wakeup_switch_tbn);
        mWakeUpTbn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                setWakeUp(isChecked);
                FlowerCollector.onEvent(getActivity().getApplicationContext(), getString(R.string.iflyvoice) + "-" + getString(R.string.voice_wakeup), "" + isChecked);
            }
        });
        mWakeUpTbn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

//        mSrEchoTbn = (ToggleButton) v.findViewById(R.id.voice_srecho_switch_tbn);
//        mSrEchoTbn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
//            @Override
//            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//                setSrEcho(isChecked);
//            }
//        });


        mGenderRecTbn = (ToggleButton) v.findViewById(R.id.voice_genderrec_switch_tbn);
        mGenderRecTbn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mGenderRecTbn.isChecked()) {
                    setGenderRecEnable(true);
                } else {
                    setGenderRecEnable(false);
                }
            }
        });


        mSpeakerConfig = SpeakerConfig.getInstance(getActivity());
        mSpeakerTv = (TextView) v.findViewById(R.id.voice_speaker_value_tv);
        mSpeakerLv = (InnerListView) v.findViewById(R.id.voice_speaker_listview);
        CommonRadioGroupAdpt adpt = new CommonRadioGroupAdpt(getActivity());
        int len = mSpeakerConfig.getSpeakerCount();
        for (int i = 0; i < len; i++) {
            adpt.addItem(
                    new CommonRadioButtonBean(mSpeakerConfig.getSpeakerWithDescAt(i),
                            mSpeakerConfig.getSpeakerIdAt(i)));
        }
        mSpeakerLv.setAdapter(adpt);
        mSpeakerLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                FlowerCollector.onEvent(getActivity().getApplicationContext(), getString(R.string.iflyvoice) + "-" + getString(R.string.voice_speaker), "" + mSpeakerConfig.getSpeakerAt(position));
                mSpeakerTv.setText(mSpeakerConfig.getSpeakerAt(position));
                mSpeakerConfig.setSpeakerAt(position);
                FlyLog.d(TAG, "speaker id: " + mSpeakerConfig.getSpeakerIdAt(position));
                mNaviSetting.setSpeaker(mSpeakerConfig.getSpeakerIdAt(position));
                if (mTtsSession == null) {
                    mTtsSession = TtsSessionManager.getInstance().getTtsSession();
                    mTtsSession.sessionStart(new TtsListener() {
                        @Override
                        public void onPlayBegin() {
                            FlyLog.d(TAG, "begin");
                        }

                        @Override
                        public void onPlayCompleted() {
                            FlyLog.d(TAG, "completed");
                            if (mhasAudioFocusGained) {
                                mAudioManager.abandonAudioFocus(mFocusListener);
                                mhasAudioFocusGained = false;
                            }
                        }

                        @Override
                        public void onPlayInterrupted() {
                            FlyLog.d(TAG, "interrupted");
                        }

                        @Override
                        public void onProgressReturn(int i, int i1) {
                            FlyLog.d(TAG, "progress");
                        }
                    }, AudioManager.STREAM_SYSTEM);
                }

                if (!mhasAudioFocusGained) {
                    int gain = mAudioManager.requestAudioFocus(mFocusListener, AudioManager.STREAM_SYSTEM,
                            AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK);
                    if (gain == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
                        mhasAudioFocusGained = true;
                    }
                }
                String tts = setSpeaker(getString(R.string.voice_speaker_tts_format,
                                mSpeakerConfig.getSpeakerAt(position)),
                        mSpeakerConfig.getSpeakerIdAt(position));
                mTtsSession.startSpeak(tts);
            }
        });
    }

    public void renew() {
        mWakeUpTbn.setChecked(getWakeUp());
//        mSrEchoTbn.setChecked(getSrEcho());
        mSpeakerTv.setText(mSpeakerConfig.getSpeaker());
        mSpeakerLv.setItemChecked(mSpeakerConfig.getSpeakerPosition(), true);
        mGenderRecTbn.setChecked(getGenderRecEnable());
    }


    @Override
    public void processCommandline(String cmd) {

    }

    @Override
    public String[] getCommands() {
        return CMD;
    }

    private boolean getGenderRecEnable() {
        return SystemProperties.getBoolean(GENDER_PROPERTY, GENDER_PROPERTY_DEFAULT_VALUE);
    }

    private void setGenderRecEnable(boolean enable) {
        if (getGenderRecEnable() != enable) {
            SystemProperties.set(GENDER_PROPERTY, Boolean.toString(enable));
            getActivity().sendBroadcast(new Intent("com.iflytek.autofly.GENDER_PROPERTY"));
        }
    }

    private String setSpeaker(String text, int speakerId) {
        StringBuilder builder = new StringBuilder();
        builder.append("[m");
        builder.append(speakerId);
        builder.append("]");
        builder.append(text);
        return builder.toString();
    }

    private boolean getWakeUp() {
        return SystemProperties.getBoolean(WAKEUP_PROPERTY,
                WAKEUP_PROPERTY_DEFAULT_VALUE);
    }

    private void setWakeUp(boolean enable) {
        SystemProperties.set(WAKEUP_PROPERTY, Boolean.toString(enable));
        getActivity().sendBroadcast(new Intent("com.iflytek.autofly.WAKEUP_PROPERTY"));
    }

    private boolean getSrEcho() {
        return SystemProperties.getBoolean(SRECHO_PROPERTY,
                SRECHO_DEFAULT_VALUE);
    }

    private void setSrEcho(boolean enable) {
        SystemProperties.set(SRECHO_PROPERTY, Boolean.toString(enable));
    }
}
